package com.eldos.ownerinfo;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Bitmap.*;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RemoteViews;
import android.content.pm.PackageManager;

/*
import android.widget.Toast;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
*/

public class OwnerInfoWidget extends AppWidgetProvider {

	String noteText;
	int action;
	String actionParams;
	boolean hideCaption = false;
	int customColor = 0x24A1AAC0;
	int customTextColor = 0xFFFFFFFF;
    int fontSize = 12;

	private boolean readPrefs(Context context)
	{
		SharedPreferences settings = null;

    	// Bug alert: the call to getDefaultSharedPreferences will crash the application
    	// if preferences have not been created beforehand
    	try {
    		settings = PreferenceManager.getDefaultSharedPreferences(context);
    	}
    	catch (Exception x) {
    		// just suppress the crash
    	}

    	noteText = context.getString(R.string.defNoteText);

    	action = OwnerInfoConst.actionCall;
    	actionParams = "";
    	hideCaption = false;
    	customTextColor = 0xFFFFFFFF;
    	customColor = 0x24A1AAC0;

    	boolean result = false;

    	if (settings != null)
    	{
    		String svalue = settings.getString(OwnerInfoConst.settingNoteText, "");
	    	if (svalue.length() != 0)
	    	{
	    		noteText = svalue;
	    		result = true;
	    	}

	    	int ivalue;

	    	svalue = settings.getString(OwnerInfoConst.settingAction, "0");
	    	try {
	    		ivalue = Integer.parseInt(svalue);
	    	}
	    	catch (Exception e)
	    	{
	    		ivalue = 0;
	    	}
	    	if (ivalue != 0)
	    	{
	    		action = ivalue;
	    		result = true;
	    	}

	    	switch (action) {
                case OwnerInfoConst.actionCall:
                      svalue = settings.getString(OwnerInfoConst.settingPhoneNumber, "");
                      break;
                case OwnerInfoConst.actionSMS:
                    svalue = settings.getString(OwnerInfoConst.settingSMSNumber, "");
                    break;
                case OwnerInfoConst.actionEMail:
                    svalue = settings.getString(OwnerInfoConst.settingEMail, "");
                    break;
                case OwnerInfoConst.actionNothing:
                    svalue = settings.getString(OwnerInfoConst.settingNothing, "");
                    break;
	    	}
	    	actionParams = svalue;

	    	hideCaption = settings.getBoolean(OwnerInfoConst.settingHideCaption, false);
	    	customColor = settings.getInt(OwnerInfoConst.settingCustomColor, 0x24A1AAC0);
	    	customTextColor = settings.getInt(OwnerInfoConst.settingCustomTextColor, 0xFFFFFFFF);

            svalue = settings.getString(OwnerInfoConst.settingFontSize, "0");
            try {
                ivalue = Integer.parseInt(svalue);
            }
            catch (Exception e)
            {
                ivalue = 0;
            }
            if (ivalue != 0)
            {
                fontSize = ivalue;
                result = true;
            }
        }

    	return result;
	}

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        // read settings
    	boolean prefsRead = readPrefs(context);

        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];
            updateOwnerInfoWidget(context, appWidgetManager, appWidgetId, noteText, action, actionParams, prefsRead);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(OwnerInfoConst.broadcastActionUpdate)) {

        	boolean prefsRead = readPrefs(context);

        	// my widget supports multiple instances so I needed to uniquely identify them like this
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, OwnerInfoWidget.class));

            final int N = appWidgetIds.length;
            for(int i=0; i<N; i++) {
                int appWidgetId = appWidgetIds[i];
                updateOwnerInfoWidget(context, appWidgetManager, appWidgetId, noteText, action, actionParams, prefsRead);
            }
        }
        super.onReceive(context, intent);
    }

    void updateOwnerInfoWidget(Context context, AppWidgetManager appWidgetManager,
            int appWidgetId, String noteText, int action, String actionParams, boolean prefsRead) {

    	// Create RemoteViews
    	RemoteViews views;

    	//appWidgetManager.getAppWidgetInfo(appWidgetId).

    	int screenWidth, screenHeight;
		screenWidth = context.getResources().getDisplayMetrics().widthPixels;
		screenHeight = context.getResources().getDisplayMetrics().heightPixels;

		int density = context.getResources().getDisplayMetrics().densityDpi;

		boolean isLandscape = screenWidth > screenHeight;

		views = new RemoteViews(context.getPackageName(), R.layout.ownerinfowidget_provider);
/*
		int wW, wH;
		if (isLandscape)
		{
			wW = 424 * density / DisplayMetrics.DENSITY_DEFAULT;
			wH = 74 * density / DisplayMetrics.DENSITY_DEFAULT;
		}
		else
		{
			wW = 294 * density / DisplayMetrics.DENSITY_DEFAULT;
			wH = 72 * density / DisplayMetrics.DENSITY_DEFAULT;
		}

		Bitmap proxy = Bitmap.createBitmap(wW, wH, Config.ARGB_8888);
		Canvas c = new Canvas(proxy);
		RectF rect = new RectF(0, 0, wW, wH);
		Paint paint = new Paint();
		paint.setARGB(0, 0, 0, 0);
		c.drawRect(rect, paint);

		// draw background
		paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG );
		paint.setColor(customColor);
		c.drawRoundRect(rect, 5, 5, paint);

		// draw border
		paint.setStyle(Paint.Style.STROKE);
		paint.setARGB(192, 192, 192, 192);
		c.drawRoundRect(rect, 5, 5, paint);

		views.setImageViewBitmap(R.id.backimage, proxy);
*/
		views.setInt(R.id.TotalLayout, "setBackgroundColor", customColor);

        views.setTextColor(R.id.captiontext, customTextColor);
    	views.setTextColor(R.id.notetext, customTextColor);

        int capFontSize;
        if (fontSize < 10)
        	capFontSize = fontSize + 1;
        else
			capFontSize = fontSize + 2;

        views.setFloat(R.id.captiontext, "setTextSize", capFontSize);
        views.setFloat(R.id.notetext, "setTextSize", fontSize);

    	if (hideCaption)
    		views.setViewVisibility(R.id.captiontext, View.GONE);
        else
            views.setViewVisibility(R.id.captiontext, View.VISIBLE);
    	// set owner note
    	views.setTextViewText(R.id.notetext, noteText);

    	Intent intent = null;

    	boolean noNewTask = false;

    	//Toast toast;

		PackageManager packageManager = context.getPackageManager();
		boolean phone = (packageManager != null && ((packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_GSM) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA))));
		if (!phone)
		{
			TelephonyManager tm=(TelephonyManager ) context.getSystemService(Context.TELEPHONY_SERVICE);
			phone = (tm != null) && (tm.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN);
		}

		if (!phone && (action == OwnerInfoConst.actionCall || action == OwnerInfoConst.actionSMS))
			action = OwnerInfoConst.actionNothing;

    	// set button image
    	if (prefsRead && phone && action == OwnerInfoConst.actionCall)
		{
			views.setViewVisibility(R.id.button, View.VISIBLE);
			views.setImageViewResource(R.id.button, R.drawable.phone);
			intent = new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:" + actionParams));
		}
		else
		if (prefsRead && phone && action == OwnerInfoConst.actionSMS)
		{
			views.setViewVisibility(R.id.button, View.VISIBLE);
    		views.setImageViewResource(R.id.button, R.drawable.sms);
    		intent = new Intent(context, OwnerInfoSMSActivity.class);
    		noNewTask = true;
		}
		else
		if (prefsRead && phone && action == OwnerInfoConst.actionEMail)
		{
    		views.setViewVisibility(R.id.button, View.VISIBLE);
    		views.setImageViewResource(R.id.button, R.drawable.email);

    		intent = new Intent(android.content.Intent.ACTION_SEND);
    		intent.setType("text/message");
    		String aEmailList[] = { actionParams };
    		intent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
		}
		else
		if (prefsRead)
		{
    		views.setViewVisibility(R.id.button, View.GONE);
    		intent = null;
    	}
		else
		{
			views.setImageViewResource(R.id.button, R.drawable.configure);
			intent = new Intent(context, OwnerInfoWidgetConfigure.class);
		}

		// Create an Intent to launch proper activity

    	PendingIntent pendingIntent = null;

    	if (intent != null)
    	{
    		if (!noNewTask)
    			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		else
    			intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    		pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    		views.setOnClickPendingIntent(R.id.button, pendingIntent);
    	}

    	// set main text action
    	// Create an Intent to launch proper activity
    	if (!prefsRead)
    		intent = new Intent(context, OwnerInfoWidgetConfigure.class);
    	else
    		intent = new Intent(context, OwnerInfoDetails.class);
    	pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    	views.setOnClickPendingIntent(R.id.notetext, pendingIntent);
    	views.setOnClickPendingIntent(R.id.captiontext, pendingIntent);
    	views.setOnClickPendingIntent(R.id.widgetbody, pendingIntent);
    	views.setOnClickPendingIntent(R.id.widgetBoundary, pendingIntent);

    	views.setViewVisibility(R.id.widgetBoundary, View.VISIBLE);

    	// Tell the widget manager to update
    	appWidgetManager.updateAppWidget(appWidgetId, views);

    	//Toast toast = Toast.makeText(context, "Widget updated", Toast.LENGTH_LONG);
		//toast.show();
    }
}